package com.jspgou.cms.action.front;

import static com.jspgou.cms.Constants.SHOP_SYS;
import static com.jspgou.cms.Constants.STORE_SYS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.util.UrlPathHelper;

import com.jspgou.cms.entity.Exended;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.entity.StoreCategory;
import com.jspgou.cms.manager.ExendedMng;
import com.jspgou.cms.manager.KeyWordMng;
import com.jspgou.cms.manager.StoreCategoryMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.web.WebErrors;
import com.jspgou.core.web.front.FrontHelper;
import com.jspgou.core.web.front.URLHelper;
import com.jspgou.core.web.front.URLHelper.PageInfo;

@Controller
public class SearchAct implements ServletContextAware {
	private static final Logger log = LoggerFactory.getLogger(SearchAct.class);
	
	private static final String SEARCH_INPUT = "tpl.searchInput";
	/*
	 * 主站商品搜索页
	 */
	private static final String SEARCH_RESULT = "tpl.searchResult";
	/*
	 * 店铺商品搜索页
	 */
	private static final String SEARCH_STORE_RESULT = "tpl.searchStoreResult";
	/*
	 * 店铺类目分类页
	 */
	private static final String SEARCH_STORE_CATEGORY = "tpl.searchStoreCategory";


	@RequestMapping(value = "/search*.jspx", method = RequestMethod.GET)
	public String search(HttpServletRequest request,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		UrlPathHelper helper = new UrlPathHelper();
		String queryString = helper.getOriginatingQueryString(request);
		int pageNo = URLHelper.getPageNo(request);
		String url = request.getRequestURL().toString();
		PageInfo info = URLHelper.getPageInfo(request);
		ShopFrontHelper.setDynamicPageData(request, model, web, url, info.getHrefFormer(), info.getHrefLatter(), pageNo);
		model.addAttribute("pageSize", getpageSize(request));
		model.addAttribute("orderBy",getOrderBy(request));
		model.addAttribute("startPrice", getStartPrice(request));
		model.addAttribute("endPrice", getEndPrice(request));
		String q = RequestUtils.getQueryParam(request, "q");
		q=StringUtils.trim(q);
		q=parseKeywords(q);
		String ctgId = RequestUtils.getQueryParam(request, "ctgId");
		ctgId=StringUtils.trim(ctgId);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		if (StringUtils.isBlank(q) && StringUtils.isBlank(ctgId)) {
			model.remove("q");
			model.remove("ctgId");
			return web.getTplSys(SHOP_SYS, MessageResolver.getMessage(request,
					SEARCH_INPUT), request);
		} else {
			model.addAttribute("q", q);
			if(StringUtils.isBlank(ctgId)){
				model.addAttribute("ctgId",null);
			}else{
				model.addAttribute("ctgId", Integer.valueOf(ctgId));
			}
			keyWordMng.save(q);
//			model.addAttribute("queryString",queryString);
			return web.getTplSys(SHOP_SYS, MessageResolver.getMessage(request,
					SEARCH_RESULT), request);
		}
	}
	
	@RequestMapping(value = "/searchStore*.jspx", method = RequestMethod.GET)
	public String searchStore(HttpServletRequest request,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		UrlPathHelper helper = new UrlPathHelper();
		String queryString = helper.getOriginatingQueryString(request);
		String q = RequestUtils.getQueryParam(request, "q");
		q=StringUtils.trim(q);
		String ctgId = RequestUtils.getQueryParam(request, "ctgId");
		ctgId=StringUtils.trim(ctgId);
		String beginPrice = RequestUtils.getQueryParam(request, "beginPrice");
		beginPrice=StringUtils.trim(beginPrice);
		String endPrice = RequestUtils.getQueryParam(request, "endPrice");
		endPrice=StringUtils.trim(endPrice);
		Store store=CmsUtils.getStore(request);
		String storeId=store.getId().toString();
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		if (StringUtils.isBlank(q) && StringUtils.isBlank(ctgId)&& StringUtils.isBlank(storeId)) {
			model.remove("q");
			model.remove("ctgId");
			model.remove("storeId");
			model.remove("beginPrice");
			model.remove("endPrice");
			return web.getTplSys(SHOP_SYS, MessageResolver.getMessage(request,
					SEARCH_INPUT), request);
		} else {
			model.addAttribute("q", q);
			keyWordMng.save(q);
			if(StringUtils.isBlank(ctgId)){
				model.addAttribute("ctgId",null);
			}else{
				model.addAttribute("ctgId", Integer.valueOf(ctgId));
			}
			if(StringUtils.isBlank(storeId)){
				model.addAttribute("storeId",null);
			}else{
				model.addAttribute("storeId", Long.valueOf(storeId));
			}
			model.addAttribute("queryString",queryString);
			ShopFrontHelper.setStoreCommonData(request, model, web, store);
			String tmp=store.getStorePath();
			model.addAttribute("flag", 1);
			model.addAttribute("beginPrice",beginPrice);
			model.addAttribute("endPrice", endPrice);
			return web.getStoreTemplate(tmp,STORE_SYS,  MessageResolver.getMessage(request,
					SEARCH_STORE_RESULT), request);
		}
	}
	
	@RequestMapping(value = "/storeCategoryList*.jspx", method = RequestMethod.GET)
	public String storeCategoryList(Long storeCategoryId,HttpServletRequest request,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		Store store=CmsUtils.getStore(request);
		WebErrors errors=validateStore(store.getForbidden(),request);
		if (errors.hasErrors()) {
			return FrontHelper.showError(errors, web, model, request);
		}
		StoreCategory storeCategory=storeCategoryMng.findById(storeCategoryId);
		String tmp=store.getStorePath();
		model.addAttribute("store", store);
		model.addAttribute("storeCategory", storeCategory);
		ShopFrontHelper.frontPageData(request, model);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.setStoreCommonData(request, model, web, store);
		return web.getStoreTemplate(tmp,STORE_SYS,  MessageResolver.getMessage(request,
				SEARCH_STORE_CATEGORY), request);
	}
	
	private WebErrors validateStore(boolean status, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
	    if(status){
	    	errors.addError("店铺已经冻结");
	    }
	
		return errors;
	}
	
	public Integer getpageSize(HttpServletRequest request){
		String pageSize = RequestUtils.getQueryParam(request, "pageSize");
		Integer pagesize = null;
		if (!StringUtils.isBlank(pageSize)) {
			pagesize = Integer.parseInt(pageSize);
		}
		if(pagesize==null){
			pagesize = 16;
		}
		return pagesize;
	}
	
	public Integer getStartPrice(HttpServletRequest request){
		String startPrice=RequestUtils.getQueryParam(request, "startPrice");
		Integer start=null;
		if(!StringUtils.isBlank(startPrice)){
			if(!startPrice.equals("￥")){				
				start=Integer.parseInt(startPrice);
			}else{
				start=0;
			}
		}
		if(start==null){
			start=0;
		}
		return start;
	}
	
	public Integer getEndPrice(HttpServletRequest request){
		String endPrice=RequestUtils.getQueryParam(request, "endPrice");
		Integer end=null;
		if(!StringUtils.isBlank(endPrice)){
			if(!endPrice.equals("￥")){				
				end=Integer.parseInt(endPrice);
			}else{
				end=0;
			}
		}
		if(end==null){
			end=0;
		}
		return end;
	}
	
	public Integer getOrderBy(HttpServletRequest request){
		String orderBy = RequestUtils.getQueryParam(request, "orderBy");
		Integer orderby = null;
		if (!StringUtils.isBlank(orderBy)) {
			orderby = Integer.parseInt(orderBy);
		}
		if(orderby==null){
			orderby = 0;
		}
		return orderby;
	}
	
	public static String parseKeywords(String q){
		try {
			String regular = "[\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:\\\\]";
			Pattern p = Pattern.compile(regular);
			Matcher m = p.matcher(q);
			String src = null;
			while (m.find()) {
				src = m.group();
				q = q.replaceAll("\\" + src, ("\\\\" + src));
			}
			q = q.replaceAll("AND", "and").replaceAll("OR", "or").replace("NOT", "not");
		} catch (Exception e) {
		}
		return  q;
	}
	
	@Autowired
	private ExendedMng exendedMng;
	@Autowired
	private StoreCategoryMng storeCategoryMng;
	@Autowired
	private KeyWordMng keyWordMng;

	private ServletContext servletContext;

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
